package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.dubbo.api.BlackListApi;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.SettingsApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.domain.Question;
import com.tanhua.model.domain.Settings;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.DeleteMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SettingsService {

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private SettingsApi settingsApi;

    @DubboReference
    private BlackListApi blackListApi;
    @DubboReference
    private FriendApi friendApi;
    @DubboReference
    private UserLikeApi userLikeApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private MessagesService messagesService;
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private VisitorsApi visitorsApi;


    //查询通用设置
    public SettingsVo settings() {
        SettingsVo vo = new SettingsVo();
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        vo.setId(userId);
        //2、获取用户的手机号码
        vo.setPhone(UserHolder.getMobile());
        //3、获取用户的陌生人问题
        Question question = questionApi.findByUserId(userId);
        String txt = question == null ? "你喜欢java吗？" : question.getTxt();
        vo.setStrangerQuestion(txt);
        //4、获取用户的APP通知开关数据
        Settings settings = settingsApi.findByUserId(userId);
        if(settings != null) {
            vo.setGonggaoNotification(settings.getGonggaoNotification());
            vo.setPinglunNotification(settings.getPinglunNotification());
            vo.setLikeNotification(settings.getLikeNotification());
        }
        return vo;
    }

    //保存陌生人问题
    public void saveQuestion(String content) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用api查询当前用户的陌生人问题
        Question question = questionApi.findByUserId(userId);
        //3、判断问题是否存在
        if(question == null) {
            //3.1 如果不存在，保存
            question = new Question();
            question.setUserId(userId);
            question.setTxt(content);
            questionApi.save(question);
        }else {
            //3.2 如果存在，更新
            question.setTxt(content);
            questionApi.update(question);
        }
    }

    //通知设置
    public void saveSettings(Map map) {
        boolean likeNotification = (Boolean) map.get("likeNotification");
        boolean pinglunNotification = (Boolean) map.get("pinglunNotification");
        boolean gonggaoNotification = (Boolean)  map.get("gonggaoNotification");
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、根据用户id，查询用户的通知设置
        Settings settings = settingsApi.findByUserId(userId);
        //3、判断
        if(settings == null) {
            //保存
            settings = new Settings();
            settings.setUserId(userId);
            settings.setPinglunNotification(pinglunNotification);
            settings.setLikeNotification(likeNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.save(settings);
        }else {
            settings.setPinglunNotification(pinglunNotification);
            settings.setLikeNotification(likeNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.update(settings);
        }
    }

    //分页查询黑名单列表
    public PageResult blacklist(int page, int size) {
        //1、获取当前用户的id
        Long userId = UserHolder.getUserId();
        //2、调用API查询用户的黑名单分页列表  Ipage对象
        IPage<UserInfo> iPage = blackListApi.findByUserId(userId,page,size);
        //3、对象转化，将查询的Ipage对象的内容封装到PageResult中
        PageResult pr = new PageResult(page,size, (int) iPage.getTotal(),iPage.getRecords());
        //4、返回
        return pr;
    }

    //取消黑名单
    public void deleteBlackList(Long blackUserId) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用api删除
        blackListApi.delete(userId,blackUserId);
    }

    //互相喜欢，喜欢，粉丝 - 统计
    public Map counts() {
        Long userId = UserHolder.getUserId();
        Integer eachLoveCount = friendApi.eachLoveCount(userId);
        Integer loveCount = userLikeApi.loveCount(userId, true);
        Integer fanCount = userLikeApi.fans(userId, true);

        Map map = new HashMap();
        map.put("eachLoveCount", eachLoveCount);
        map.put("loveCount", loveCount);
        map.put("fanCount", fanCount);
        return map;
    }

    //喜欢 - 取消
    public void notLikeUser(Long likeUserId) {
        Long userId = UserHolder.getUserId();
        userLikeApi.remove(userId, likeUserId, true);
        messagesService.deletecontacts(likeUserId);
        String key = Constants.USER_LIKE_KEY + userId;
        //操作Redis set类型(无序,去重),删除喜欢的数据
        redisTemplate.opsForSet().remove(key, likeUserId.toString());
        Boolean aboolena = redisTemplate.opsForSet().isMember(key, likeUserId.toString());
        if (aboolena) {
            messagesService.deletecontacts(userId);
        }
    }

    //粉丝 - 喜欢
    public void likeUser(Long likeUserId) {
        Long userId = UserHolder.getUserId();
        //1、调用API，保存喜欢数据(保存到MongoDB中)
        Boolean save = userLikeApi.saveOrUpdate(userId, likeUserId, true);//(操作人id,喜欢我的用户id,喜欢)
        if (!save) {
            //失败
            throw new BusinessException(ErrorResult.error());
        }
        //2、操作redis，写入喜欢的数据，删除不喜欢的数据 (喜欢的集合，不喜欢的集合)
        redisTemplate.opsForSet().remove(Constants.USER_NOT_LIKE_KEY + userId, likeUserId.toString());
        redisTemplate.opsForSet().add(Constants.USER_LIKE_KEY + userId, likeUserId.toString());
        //添加好友
        messagesService.contacts(likeUserId);
    }

    //互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
    public PageResult findFriends(Integer page, Integer pagesize, String nickname, Long type) {
        Long userId = UserHolder.getUserId();
        if (type == 1) {//互相喜欢
            PageResult pr = messagesService.findFriends(page, pagesize, nickname);
            return pr;
        } else if (type == 2) { //我喜欢
            List<UserLike> list = userLikeApi.findByUserId(UserHolder.getUserId(),page,pagesize);
            if(CollUtil.isEmpty(list)) {
                return new PageResult();
            }
            //2、提取数据列表中的好友id
            List<Long> likeUserIds = CollUtil.getFieldValues(list, "likeUserId", Long.class);
            //3、调用UserInfoAPI查询好友的用户详情
            UserInfo info = new UserInfo();
            info.setNickname(nickname);
            Map<Long, UserInfo> map = userInfoApi.findByIds(likeUserIds, info);
            //4、构造VO对象
            List<UserInfo> vos = new ArrayList<>();
            for (UserLike userLike : list) {
                UserInfo userInfo = map.get(userLike.getLikeUserId());
                if(userInfo != null) {
                    vos.add(userInfo);
                }
            }
            return new PageResult(page,pagesize,0,vos);
        } else if (type == 3) { //粉丝
            List<UserLike> list = userLikeApi.findByUserIds(UserHolder.getUserId(),page,pagesize);
            if(CollUtil.isEmpty(list)) {
                return new PageResult();
            }
            //2、提取数据列表中的好友id
            List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
            //3、调用UserInfoAPI查询好友的用户详情
            UserInfo info = new UserInfo();
            info.setNickname(nickname);
            Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, info);
            //4、构造VO对象
            List<UserInfo> vos = new ArrayList<>();
            for (UserLike userLike : list) {
                UserInfo userInfo = map.get(userLike.getUserId());
                if(userInfo != null) {
                    vos.add(userInfo);
                }
            }
            return new PageResult(page,pagesize,0,vos);
        } else {// 谁看过我
            //调用API查询数据列表 List<Visitors>
            List<Visitors> list =  visitorsApi.queryMyVisitor(UserHolder.getUserId());
            if(CollUtil.isEmpty(list)) {
                return new PageResult();
            }
            //3、提取用户的id
            List<Long> userIds = CollUtil.getFieldValues(list, "visitorUserId", Long.class);
            //4、查看用户详情
            Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
            //5、构造返回
            List<ContactVo> vos = new ArrayList<>();
            for (Visitors visitors : list) {
                UserInfo userInfo = map.get(visitors.getVisitorUserId());
                if(userInfo != null) {
                    ContactVo vo = ContactVo.init(userInfo);
                    Double score = visitors.getScore();
                    int fateValue = new Double(score).intValue();
                    vo.setMatchRate(fateValue);
                    vos.add(vo);
                }
            }
            return new PageResult(page,pagesize,0,vos);
        }
    }

    //是否喜欢（新增接口）
    public Boolean alreadyLove(Long likeUserId) {
        Long userId = UserHolder.getUserId();
        UserLike userLike = userLikeApi.alreadyLove(userId,likeUserId);
        Boolean isLike = userLike.getIsLike();
        return isLike;
    }
}
